package org.example.node;

/**
 * @author liyishan
 * @date 2024/9/27 10:49
 * @apiNote
 */

public class Test00023MergeKLists {
    public ListNode mergeKLists(ListNode[] lists) {
        ListNode ans = null;
        for(int i = 0; i < lists.length; i++) {
            ans = mergeTwoLists(ans, lists[i]);
        }
        return ans;
    }


    public ListNode mergeTwoLists(ListNode a,ListNode b){
        if(a == null || b == null){
            return a == null? b : a;
        }
        ListNode head = new ListNode(0);
        ListNode tail = head;
        ListNode a1 = a,b1 = b;
        while(a1 != null && b1 != null){
            if(a1.val <= b1.val){
                tail.next = a1;
                a1 = a1.next;
            }else{
                tail.next = b1;
                b1 = b1.next;
            }
            tail = tail.next;
        }
        tail.next = a1 == null? b1 : a1;
        return head.next;
    }
}
